package cn.jstars.datatocloud.modules.monitor.task;

import java.util.List;
import java.util.Map;

import org.nutz.lang.Lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;

import cn.jstars.datatocloud.common.cache.Cache;
import cn.jstars.datatocloud.common.consts.Consts.DBConst;
import cn.jstars.datatocloud.common.consts.Consts.DataType;
import cn.jstars.datatocloud.common.utils.DataUtil;
import cn.jstars.datatocloud.common.utils.PageUtil;
import cn.jstars.datatocloud.modules.base.MqService;
import cn.jstars.datatocloud.modules.monitor.entity.Toimachinestatus;
import cn.jstars.datatocloud.modules.monitor.service.MonitorService;

/**
 * TMS级联任务类（除天表外）
 * 
 * @author Elvish
 *
 */
public class TMSTask implements Runnable {

	private static final Logger LOGGER = LoggerFactory.getLogger(TMSTask.class);

	private MqService mqService;
	private MonitorService monitorService;
	private String year;

	public TMSTask(MqService mqService, MonitorService monitorService, int year) {
		this.mqService = mqService;
		this.monitorService = monitorService;
		this.year = year + "";
	}

	@Override
	public void run() {

		try {

			List<Toimachinestatus> dataList = monitorService.findEquipstatusWithoutUpload(year);

			// 没有就退出
			if (Lang.isEmpty(dataList)) {
				return;
			}

			// 切分数据
			List<List<Toimachinestatus>> pageList = PageUtil.paging(dataList, 500);

			for (List<Toimachinestatus> list : pageList) {

				// 组装数据
				Map<String, Object> dataMap = Maps.newHashMap();
				dataMap.put("type", "Toimachinestatus");
				dataMap.put("data", JSON.toJSONString(list));

				// 封装发送数据
				String sendMsg = DataUtil.getMessage(DataType.MONITOR_ANOTHER_DATA, DBConst.COUNTON_PREFIX + year,
						DBConst.TOIMACHINESTATUS_EQUIPSTATUS, Cache.factoryId, dataMap);

				try {
					// 发送数据
					mqService.convertAndSend(Cache.cloudMQQueueName, sendMsg);
				} catch (Exception e) {
					LOGGER.error("发送TMS（除天表外）数据异常，睡30秒", e);
					Thread.sleep(30000);
					continue;
				}

				// 更新数据库状态
				monitorService.updateEquipstatusUploadStatus(list, year);

			}

		} catch (Exception e) {
			LOGGER.error("TMS（除天表外）级联失败", e);
		}

	}

}
